<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="考试名称" prop="examName">
        <el-input v-model="formData.examName" placeholder="请输入考试名称" />
      </el-form-item>
      <el-form-item label="考试类型" prop="examType">
        <el-select v-model="formData.examType" placeholder="请选择考试类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.EXAM_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考试时间" prop="examDate">
        <el-date-picker
          v-model="formData.examDate"
          type="date"
          value-format="x"
          placeholder="选择考试时间"
        />
      </el-form-item>
      <el-form-item label="考试班级" prop="classIds">
        <el-select
          v-model="formData.classIds"
          multiple
          placeholder="请选择班级"
          style="width: 100%"
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option
            v-for="classItem in classList"
            :key="classItem.id"
            :label="classItem.className"
            :value="classItem.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="总分" prop="totalScore">
        <el-input v-model="formData.totalScore" placeholder="总分" :disabled="true" />
      </el-form-item>
      <el-form-item label="科目配置" prop="subjectConfig">
        <div class="subject-config">
          <div v-for="(subject, index) in subjects" :key="index" class="subject-item">
            <el-input
              v-model="subject.name"
              placeholder="科目名称"
              style="width: 140px; margin-right: 10px;"
              @input="onSubjectNameChange(subject, $event)"
            />
            <el-input-number
              v-model="subject.score"
              :min="0"
              :max="300"
              placeholder="分数"
              style="width: 120px; margin-right: 10px;"
              @change="updateSubjectConfig"
            />
            <el-button
              type="danger"
              size="small"
              @click="removeSubject(index)"
              :disabled="subjects.length <= 1"
            >
              删除
            </el-button>
          </div>
          <el-button type="primary" size="small" @click="addSubject" style="margin-top: 10px;">
            添加科目
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="考试说明" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_STATE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ExamTestApi, ExamTestVO } from '@/api/system/examtest'
import { ExamClassApi, ExamClassVO } from '@/api/system/examclass'
import { useUserStore } from '@/store/modules/user'

/** 考试信息 表单 */
defineOptions({ name: 'ExamTestForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStore() // 用户信息

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const classList = ref<ExamClassVO[]>([]) // 班级列表
const formData = ref({
  id: undefined,
  examName: undefined,
  examType: undefined,
  classIds: [],
  teacherId: undefined,
  examDate: undefined,
  totalScore: undefined,
  subjectConfig: undefined,
  description: undefined,
  status: undefined,
})

// 科目配置相关数据
const subjects = ref([
  { name: '语文', score: 150 },
  { name: '数学', score: 150 },
  { name: '英语', score: 150 },
  { name: '物理', score: 100 },
  { name: '化学', score: 100 },
  { name: '生物', score: 100 }
])
const formRules = reactive({
  examName: [{ required: true, message: '考试名称不能为空', trigger: 'blur' }],
  examType: [{ required: true, message: '考试类型不能为空', trigger: 'change' }],
  classIds: [{ required: true, message: '请选择班级', trigger: 'change' }],
  teacherId: [{ required: true, message: '出题老师ID不能为空', trigger: 'blur' }],
  examDate: [{ required: true, message: '考试时间不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

// 科目配置相关方法
const addSubject = () => {
  subjects.value.push({ name: '', score: 100 })
  updateSubjectConfig()
}

// 根据科目名称获取默认分数
const getDefaultScore = (subjectName: string) => {
  const mainSubjects = ['语文', '数学', '英语']
  const scienceSubjects = ['物理', '化学', '生物']

  if (mainSubjects.includes(subjectName)) {
    return 150
  } else if (scienceSubjects.includes(subjectName)) {
    return 100
  } else {
    return 100 // 其他科目默认100分
  }
}

// 处理科目名称变化
const onSubjectNameChange = (subject: any, newName: string) => {
  subject.name = newName
  // 如果分数还是默认值，则根据新的科目名称更新分数
  const defaultScore = getDefaultScore(newName)
  if (subject.score === 100 || subject.score === 150) {
    subject.score = defaultScore
  }
  updateSubjectConfig()
}

const removeSubject = (index: number) => {
  subjects.value.splice(index, 1)
  updateSubjectConfig()
}

const updateSubjectConfig = () => {
  const config = {
    subjects: subjects.value.filter(subject => subject.name.trim() !== '')
  }
  formData.value.subjectConfig = JSON.stringify(config)
  // 计算总分
  const totalScore = subjects.value.reduce((sum, subject) => {
    return sum + (subject.score || 0)
  }, 0)
  formData.value.totalScore = totalScore
}

// 解析科目配置JSON到subjects数组
const parseSubjectConfig = (configStr: string) => {
  try {
    if (configStr) {
      const config = JSON.parse(configStr)
      if (config.subjects && Array.isArray(config.subjects)) {
        subjects.value = config.subjects.map(subject => ({
          name: subject.name || '',
          score: subject.score || getDefaultScore(subject.name || '')
        }))
      }
    }
  } catch (error) {
    console.warn('解析科目配置失败:', error)
    // 如果解析失败，使用默认配置
    subjects.value = [
      { name: '语文', score: 150 },
      { name: '数学', score: 150 },
      { name: '英语', score: 150 },
      { name: '物理', score: 100 },
      { name: '化学', score: 100 },
      { name: '生物', score: 100 }
    ]
  }
}

/** 获取班级列表 */
const getClassList = async () => {
  try {
    const data = await ExamClassApi.getAllExamClasses()
    classList.value = data || []
  } catch (error) {
    console.error('获取班级列表失败:', error)
    message.error('获取班级列表失败')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 获取班级列表
  await getClassList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ExamTestApi.getExamTest(id)
      // 解析科目配置
      parseSubjectConfig(formData.value.subjectConfig)
      // 确保classIds是数组格式
      if (formData.value.classIds && !Array.isArray(formData.value.classIds)) {
        formData.value.classIds = [formData.value.classIds]
      }
    } finally {
      formLoading.value = false
    }
  } else {
    // 新增时，确保设置默认值
    formData.value.status = 1 // 默认状态为进行中
    // 确保总分正确显示
    updateSubjectConfig()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 更新科目配置
  updateSubjectConfig()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ExamTestVO
    if (formType.value === 'create') {
      await ExamTestApi.createExamTest(data)
      message.success(t('common.createSuccess'))
    } else {
      await ExamTestApi.updateExamTest(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  // 重置科目配置为默认值
  subjects.value = [
    { name: '语文', score: 150 },
    { name: '数学', score: 150 },
    { name: '英语', score: 150 },
    { name: '物理', score: 100 },
    { name: '化学', score: 100 },
    { name: '生物', score: 100 }
  ]
  
  formData.value = {
    id: undefined,
    examName: undefined,
    examType: undefined,
    classIds: [],
    teacherId: undefined, // 不设置默认值
    examDate: undefined,
    totalScore: 750, // 直接设置默认总分
    subjectConfig: undefined,
    description: undefined,
    status: 1, // 默认状态为进行中（假设1表示进行中）
  }
  
  // 先更新科目配置和总分，再重置表单字段
  updateSubjectConfig()
  
  nextTick(() => {
    formRef.value?.resetFields()
  })
}
</script>

<style scoped>
.subject-config {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.subject-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.subject-item:last-child {
  margin-bottom: 0;
}
</style>
